<?php

class JobModule extends CWebModule
{

    public $amountSkill= 2;
    public $status_issetbid =1;//có người bid tham gia dự án
    public $status_addbid = 2;//chủ dự án có thêm người làm
    public $status_contract =3; //làm hợp đồng
    public $status_endjob=4; // kết thúc dự án 
    public $satuspost_deposit = 2; // dự án đã đặt cọc
    public $bidsattus_deposit = 1;// người bid đã đặt cọc 
    public $bidsattus_addjob = 2; //có người mún nhận bạn tham gia dự án
    public $bidsattus_argee = 3; // người bid chính thức đồng ý tham gia dự án
    public $bidsattus_starst =4;//dự án bắt đầu làm.
    public $bidsattus_end = 5;//kết thúc dự án 
    public $timejob  = array('Một ngày'=>'1','2'=>'Ba ngày','3' =>'Một tuần','4'=>'Một tháng' ,'5'=>'Hai tháng','6'=>'Bốn tháng ');
    public function init()
    {
                // this method is called when the module is being created
                // you may place code here to customize the module or the application

                // import the module-level models and components
        $this->setImport(array(
            'job.models.*',
            'job.components.*',
        ));
    }
    public function beforeControllerAction($controller, $action)
    {
        if(parent::beforeControllerAction($controller, $action))
        {
    
            return true;
        }
        else
            return false;
    }
    public function getMaxBidJob($id)
    {
        $sql = "SELECT *,max(money) FROM `tbl_bidjob` WHERE job_id=$id";
        $data = Yii::app()->db->createCommand($sql)->queryRow();
        if ($data != null) {
            return $data;
        }else{
            return null;
        }
    }

    public function setJobCrontabs($name,$filerun)
    {
        $cron = new Crontab('my_crontab'); // my_crontab file will store all added jobs
 
    $jobs_obj = $cron->getJobs(); // previous jobs saved in my_crontab
 
    foreach($jobs_obj as $job)
        echo $job->getCommand();
 
    $cron->eraseJobs(); // erase all previous jobs in my_crontab
 
    // Application console job
    $cron->addApplicationJob('test', 'test1', array(), '20','*');
 
 
    // <= adds a third job with: 0 0 * * 1 /home/user/myprogram.bin 
 
    $cron->removeJob(2); // removes job with offset 2 (last added here)
 
    $cron->saveCronFile(); // save to my_crontab cronfile
 
    $cron->saveToCrontab(); // adds all my_crontab jobs to system (replacing previous my_crontab jobs)
    }

    public function getTestIdBidjob($model){// day lam ham kiem tra da bid du an hay chua. neu bid roi tra ve false, con khong tra ve true

        $result = true;
        if ($model->bidjobs != null){
            foreach ($model->bidjobs as $i){
            if ($i->user->id == Yii::app()->user->id){
                $result = false;
                break;
            }
        }
        }
        if($model->status == -1 || $model->user_id == Yii::app()->user->id){
            $result = false;
        }
        return $result;
    }
    public function setDropEventJob($time)
    {
        $name = "statusjob".strtotime($time);
        $sql = "DROP EVENT IF EXISTS $name;";
        Yii::app()->db->createCommand($sql)->execute();
    }
    public function setStatusJob($time,$status,$id)
    {
        //SET GLOBAL event_scheduler = ON;
        $name = "statusjob".strtotime($time);
        $sql = "DROP EVENT IF EXISTS $name; 
                SET GLOBAL event_scheduler = ON;
        CREATE EVENT $name ON SCHEDULE AT
                                '$time' DO UPDATE joco.tbl_job SET status=$status
                                where id =$id;";
        Yii::app()->db->createCommand($sql)->execute();
    }

    public static function getJobSubType() {
        $sql = Yii::app()->db->createCommand('select * from tbl_sub_jobtype');
        $type = CHtml::listData($sql->queryAll(), 'id', 'name');
        return $type;
    }

    public static function getMinMonney() {
        $sql = Yii::app()->db->createCommand('select * from tbl_budget where currency_id =1');
        $type = CHtml::listData($sql->queryAll(), 'minmoney', 'minmoney');
        return $type;
    }
    public static function getMaxMonney() {
        $sql = Yii::app()->db->createCommand('select * from tbl_budget where currency_id =1');
        $type = CHtml::listData($sql->queryAll(), 'maxmoney', 'maxmoney');
        return $type;
    }
    public function getCountJobType($value=0)
    {
        $criteria = new CDbCriteria();
        $criteria->join ="inner join tbl_sub_jobtype sub on subjobtype_id = sub.id where sub.jobtype_id =$value";
        return Job::model()->count($criteria);
    }
    public function createInboxmessage($jobid,$serid,$name,$content)
    {
        $model = new Inbox;
        $model->job_id = $jobid;
        $model->service_id = $serid;
        $model->name = $name;
        $model->content = $content;
        $model->status =0;
        $model->user_id = Yii::app()->user->id;
        $model->save(false);
    }

    function sendMail($title,$content,$mailuser){
        Yii::import('ext.yii-mail.YiiMailMessage');
            $message = new YiiMailMessage;
            $message->subject = $title;
            // $message->view='job';
            $message->addTo($mailuser);
            $message->setBody($content, 'text/html');
            $message->from = Yii::app()->params['adminEmail'];

            Yii::app()->mail->send($message);
    }

    static function time_diff($firstTime,$lastTime)// ham tru hai ngay cho sau,in ra ngay phut giay
    {

        // convert to unix timestamps
        $firstTime=strtotime($firstTime);
        $lastTime=strtotime($lastTime);

        // perform subtraction to get the difference (in seconds) between times
        $timeDiff=$lastTime-$firstTime;

        $day = intval($timeDiff/86400);
        $r = $timeDiff%86400;
        $hours = intval($r/3600);
        $r = $r%3600;
        $minute = intval($r/60);
        if ( $day  == 0 && $hours == 0 ){
            return $minute.' m';
        }elseif ($day == 0) {
            return "$hours h $minute m";
        }else{
            return $day."d $hours".'h';
        }
    }

    function time_diff_all($firstTime,$lastTime)// ham tru hai ngay cho sau,in ra ngay phut giay
    {

        // convert to unix timestamps
        $firstTime=strtotime($firstTime);
        $lastTime=strtotime($lastTime);

        // perform subtraction to get the difference (in seconds) between times
        $timeDiff=$lastTime-$firstTime;

        $day = intval($timeDiff/86400);
        $r = $timeDiff%86400;
        $hours = intval($r/3600);
        $r = $r%3600;
        $minute = intval($r/60);
        if ( $day  == 0 && $hours == 0 ){
            return $minute.' phút';
        }elseif ($day == 0 && $hours != 0) {
            return "$hours giờ $minute phút";
        }else{
            return $day."ngày $hours".'giờ';
        }
    }

    function timeend($firstTime,$lastTime)// ham tru hai ngay cho sau,in ra ngay phut giay
    {

        // convert to unix timestamps
        $firstTime=strtotime($firstTime);
        $lastTime=strtotime($lastTime);

        // perform subtraction to get the difference (in seconds) between times
        $timeDiff=$lastTime-$firstTime;
        $day = intval($timeDiff/86400);
        if ( $day == 0 ){
            return 0;
        }elseif($day < 0){
            return -1;
        }
        return $day;
    }

    public function getValueBudget($id)
    {
        $value  = Budget::model()->findByPk($id);
        $str1 = $value->details."($value->minmoney - $value->maxmoney)";
        return "<select name='Job[budget_id]' id='Job_budget_id'><option value='$value->id'>$str1</option></select>";
    }

    function getValueTimeJob($firstTime,$lastTime)// ham tru hai ngay cho sau,in ra ngay phut giay
    {

        // convert to unix timestamps
        $firstTime=strtotime($firstTime);
        $lastTime=strtotime($lastTime);

        // perform subtraction to get the difference (in seconds) between times
        $timeDiff=$lastTime-$firstTime;
        $day = intval($timeDiff/86400);
        $week = $day / 7;
        if ($week == 1){
            return 0;
        }elseif ($week == 4) {
            return 1;
        }else{
            return 2;
        }
    }

    public function getJobCurrency() {
        $sql = Yii::app()->db->createCommand('select * from tbl_currency');
        $type = CHtml::listData($sql->queryAll(), 'id', 'currency');
        return $type;
    }
    public function getTimeEnd()
    {
        return  array('0' => 'Thời hạn một tuần',
                       '1'=> '1 tuần đến 4 tuần ',
                       '2' => '1 tháng đến 3 tháng'  );
    }

    public function getBidWinner($model)
    {
        foreach ($model->bidjobs as $key) {
            if ($key->user_id == $model->id_winner) {
                return $key;
            }
        }
        return null;
    }

}